var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

// 当前的打包参数信息
const update_argv = {};
/**@description true: 当前的参数表示资源是需要压缩过的 false: 表示不需要压缩 */
update_argv.compress = false;
/**@description 当前打包的版本号 */
update_argv.version = "1.0";
/**@description pack_type: release / debug 模式 */
update_argv.pack_type = "debug";
/**@description 渠道名称 */
update_argv.channel = "company";
/**@description 当前游戏的分之(游戏所在的分之名称) */
update_argv.branch = "Restaurant";

function add_version(cur_version){
    const vers = cur_version.split(".");
    let pre = parseInt(vers[0]);
    let after = parseInt(vers[1]);

    if(after + 1 <= 9){
        after = after + 1;
    }else{
        pre = pre + 1;
        after = 0;
    }

    const final_version = `${pre}.${after}`;

    console.log("当前的版本号 ", cur_version, "添加后的版本号= ",final_version);
    return final_version;

}

function generator_argv() {
    const all_object = Object.keys(update_argv);

    for(const param_str of process.argv){
        for(const build_key of all_object){
            if(param_str.indexOf(build_key) == 0){
                console.log("build_key = ",build_key);
                const cte = param_str.split(":");
                if(cte[1]== "false"){
                    update_argv[build_key] = false;
                }else if(cte[0] == build_key){
                    update_argv[build_key] = cte[1];
                }
            }
        }
    }

    console.log("当前更新的版本信息 = ", update_argv);
}

generator_argv();

console.log("当前更新的版本信息 = ", process.argv);

const remote_manifest = `https://bubuduo-guesssong.oss-cn-beijing.aliyuncs.com/games_assets_update/channel/${update_argv.channel}/${update_argv.pack_type}/${update_argv.branch}/`;

var manifest = {
    packageUrl: `${remote_manifest}/versions/${update_argv.version}assert_update/remote-assets/`,
    remoteManifestUrl: `${remote_manifest}/project.manifest`,
    remoteVersionUrl: `${remote_manifest}/version.manifest`,
    version: `${update_argv.version}`,
    assets: {},
    searchPaths: [],
};

var dest = './remote-assets/';
var src = './jsb/';

// Parse arguments
var i = 2;
while ( i < process.argv.length) {
    var arg = process.argv[i];

    switch (arg) {
    case '--url' :
    case '-u' :
        const t_url = process.argv[i+1];
        var url = t_url + `versions/${update_argv.version}/assert_update/remote-assets/`;
        manifest.packageUrl = url;
        manifest.remoteManifestUrl = t_url + 'project.manifest';
        manifest.remoteVersionUrl = t_url + 'version.manifest';
        i += 2;
        break;
    case '--version' :
    case '-v' :
        manifest.version = process.argv[i+1];
        i += 2;
        break;
    case '--src' :
    case '-s' :
        src = process.argv[i+1];
        i += 2;
        break;
    case '--dest' :
    case '-d' :
        dest = process.argv[i+1];
        i += 2;
        break;
    default :
        i++;
        break;
    }
}


manifest.packageUrl.replace()
manifest.packageUrl = manifest.packageUrl;


function readDir (dir, obj) {
    var stat = fs.statSync(dir);
    if (!stat.isDirectory()) {
        return;
    }
    var subpaths = fs.readdirSync(dir), subpath, size, md5, compressed, relative;
    for (var i = 0; i < subpaths.length; ++i) {
        if (subpaths[i][0] === '.') {
            continue;
        }
        subpath = path.join(dir, subpaths[i]);
        stat = fs.statSync(subpath);
        if (stat.isDirectory()) {
            readDir(subpath, obj);
        }
        else if (stat.isFile()) {
            // Size in Bytes
            size = stat['size'];
            md5 = crypto.createHash('md5').update(fs.readFileSync(subpath)).digest('hex');
            compressed = path.extname(subpath).toLowerCase() === '.zip';

            relative = path.relative(src, subpath);
            relative = relative.replace(/\\/g, '/');
            relative = encodeURI(relative);
            relative = relative.replace("new_android_sdk/", "");
            console.log("relative = ",relative)
            obj[relative] = {
                'size' : size,
                'md5' : md5
            };
            if (compressed) {
                obj[relative].compressed = true;
            }
        }
    }
}

var mkdirSync = function (path) {
    try {
        fs.mkdirSync(path);
    } catch(e) {
        if ( e.code != 'EEXIST' ) throw e;
    }
}

// Iterate res and src folder
readDir(path.join(src, '/new_android_sdk/src'), manifest.assets);
readDir(path.join(src, '/new_android_sdk/assets'), manifest.assets);
 


var destManifest = path.join(dest, 'project.manifest');
var destVersion = path.join(dest, 'version.manifest');

mkdirSync(dest);

fs.writeFile(destManifest, JSON.stringify(manifest), (err) => {
  if (err) throw err;
  console.log('生成更新配置成功');
});


delete manifest.assets;
delete manifest.searchPaths;
fs.writeFile(destVersion, JSON.stringify(manifest), (err) => {
  if (err) throw err;
  console.log('生成版本信息成功');
});
